package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //异常情况的处理（收货地址为空、购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        //向订单表插入1条数据
        orderMapper.insert(order);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }

        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车中的数据
        shoppingCartMapper.deleteByUserId(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
        ///////////////////////////////////////////////////////
        //模拟支付成功
        paySuccess(ordersPaymentDTO.getOrderNumber());
        //返回一个空对象
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        ///////////////////////////////////////
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号" + outTradeNo);
        //通过websocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 用户端查询历史订单
     * @param dto
     * @return
     */
    @Override
    public PageResult pageQuery4User(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        dto.setUserId(BaseContext.getCurrentId());
        Page<OrderVO> page = orderMapper.pageQuery(dto);
        //判断是否查询到订单
        if(page != null || page.getTotal()>0){
            //封装每个订单的明细数据
            //遍历订单列表
            for (OrderVO orderVO : page.getResult()) {
                //根据订单id查询对应的订单明细数据
                List<OrderDetail> orderDetailList = orderDetailMapper.listByOrderId(orderVO.getId());
                //封装到订单vo中
                orderVO.setOrderDetailList(orderDetailList);
            }
        }

        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 根据订单id查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetailById(Long id) {
        Orders orders = orderMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> orderDetailList = orderDetailMapper.listByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);
        String orderDishes = getOrderDishesStr(id);
        orderVO.setOrderDishes(orderDishes);

        return orderVO;
    }

    /**
     * 用户取消订单
     *
     * @param id 订单ID
     */
    @Override
    @Transactional
    public void cancelById(Long id) throws Exception {
        // 1. 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 2. 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 3. 校验订单状态，只有在特定状态下才能取消
        Integer status = ordersDB.getStatus();

        // 3.1 如果订单已完成或已取消，直接抛出异常，不允许任何操作
        if (status.equals(Orders.COMPLETED) || status.equals(Orders.CANCELLED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 3.2 如果订单处于“已接单”或“派送中”，属于“特殊取消”场景，也抛出异常提示用户联系商家
        // （在真实业务中，这里可能不会直接抛异常，而是返回一个特定的状态码给前端，让前端引导用户操作）
        if (status.equals(Orders.CONFIRMED) || status.equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 4. 创建一个新的 Orders 对象，用于承载更新的数据
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 5. 订单处于“待接单”状态下取消，需要进行退款
        if (status.equals(Orders.TO_BE_CONFIRMED)) {
            // 5.1 调用微信支付退款接口（假设微信支付已完成）
            //模拟完成
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), // 商户订单号
//                    ordersDB.getNumber(), // 商户退款单号，为保证幂等性，通常也使用订单号
//                    ordersDB.getAmount(), // 退款金额，单位 元
//                    ordersDB.getAmount()  // 原订单金额
//            );

            // 5.2 支付状态修改为“已退款”
            orders.setPayStatus(Orders.REFUND);
        }

        // 6. 更新订单的核心状态和信息
        // 适用于“待支付”和“待接单”两种情况下的取消
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());

        // 7. 调用 Mapper 更新数据库
        orderMapper.update(orders);
    }

    /**
     * 用户再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //将原订单中的商品重新加入到购物车中
        //1.根据订单id查询订单详细信息
        List<OrderDetail> orderDetailList = orderDetailMapper.listByOrderId(id);
        //2.将订单明细数据转换为购物车数据并保存
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        for (OrderDetail orderDetail : orderDetailList) {
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
    }
    /**
     * 订单分页查询 (管理端或用户端)
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 1. 设置分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 2. 分页查询订单主表信息
        // Mapper.xml 返回的仍然是 Page<OrderVO>，只是此时 orderDishes 字段是 null
        Page<OrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 3.判断查询结果是否为空，不为空则进行处理
        if (page != null && page.getTotal() > 0) {
            // 4. 遍历订单列表
            for (OrderVO orderVO : page.getResult()) {
                // 5. 根据每个订单的ID，获取并拼接菜品字符串
                String orderDishes = getOrderDishesStr(orderVO.getId());

                // 6. 将拼接好的字符串设置到当前的 OrderVO 中
                orderVO.setOrderDishes(orderDishes);
            }
        }else{
            log.info("订单分页查询，未查询到订单数据，查询参数：{}", ordersPageQueryDTO);
        }

        // 7. 封装 PageResult 并返回
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orderId 订单ID
     * @return 拼接好的菜品字符串
     */
    private String getOrderDishesStr(Long orderId) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.listByOrderId(orderId);

        // 使用 Stream API 将每一条订单菜品信息拼接为字符串
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            // 格式：菜品名*数量;
            return x.getName() + "x" + x.getNumber() + "; "; // 优化格式，加上空格更美观
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接成一个单独的字符串
        // String.join 会自动处理分隔符，比手动拼接更高效、更安全
        return String.join("", orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        //根据状态统计订单数量
        Integer toBeConfirmed = orderMapper.countByStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countByStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO statisticsVO = OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
        return statisticsVO;
    }

    /**
     * 管理端根据id接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        //根据id修改订单状态为已接单
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 管理端根据id拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orderDB = orderMapper.getById(ordersRejectionDTO.getId());
        //只有订单处于待接单状态才能拒单
        if(orderDB == null || !orderDB.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //如果用户已经完成了支付，需要为用户退款
        if(orderDB.getPayStatus().equals(Orders.PAID)){
            //模拟退款
//            String refund = weChatPayUtil.refund(
//                    orderDB.getNumber(),
//                    orderDB.getNumber(),
//                    orderDB.getAmount(),
//                    orderDB.getAmount());
            log.info("申请退款：{}", ordersRejectionDTO);
        }
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .payStatus(Orders.REFUND)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 管理端根据id取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancerOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders orderDB = orderMapper.getById(ordersCancelDTO.getId());
        if(orderDB == null ){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //商家取消订单时，如果用户已经完成了支付，需要为用户退款
        if(orderDB.getPayStatus().equals(Orders.PAID)){
            //模拟退款
//            String refund = weChatPayUtil.refund(
//                    orderDB.getNumber(),
//                    orderDB.getNumber(),
//                    orderDB.getAmount(),
//                    orderDB.getAmount());
            log.info("申请退款：{}", ordersCancelDTO);
        }
        //取消订单其实就是将订单状态修改为“已取消”
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .cancelTime(LocalDateTime.now())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .status(Orders.CANCELLED)
                .payStatus(Orders.REFUND)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 管理端根据id派送订单
     * @param id
     */
    @Override
    public void deliveryOrder(Long id) {
        Orders orderDB = orderMapper.getById(id);
        //只有已接单（待派送）的订单可以执行派送订单操作
        if(orderDB == null || !orderDB.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //派送订单其实就是将订单状态修改为“派送中”
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 管理端根据id完成订单
     * @param id
     */
    @Override
    public void completeOrder(Long id) {
        Orders orderDB = orderMapper.getById(id);
        //只有状态为“派送中”的订单可以执行订单完成操作
        if(orderDB == null || !orderDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //完成订单其实就是将订单状态修改为“已完成”
        Orders order = Orders.builder()
                .id(id)
                .deliveryTime(LocalDateTime.now())
                .status(Orders.COMPLETED)
                .build();
        orderMapper.update(order);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orderDB = orderMapper.getById(id);
        if(orderDB == null ){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("type", 2);//消息类型，2表示催单
        map.put("orderId", id);
        map.put("content","订单号:" + orderDB.getNumber());
        //通过websocket实现催单提醒
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

}
